import 'dart:convert';

import 'package:barcode_scan/barcode_scan.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_oldman_health/api/constant.dart';
import 'package:flutter_oldman_health/api/member_service.dart';
import 'package:flutter_oldman_health/models/relation_model.dart';
import 'package:flutter_oldman_health/models/remote_control_received_model.dart';
import 'package:flutter_oldman_health/models/response_data_model.dart';
import 'package:flutter_oldman_health/pages/album/album_page.dart';
import 'package:flutter_oldman_health/pages/login_page.dart';
import 'package:flutter_oldman_health/pages/message_list_page.dart';
import 'package:flutter_oldman_health/utils/event_bus.dart';
import 'package:flutter_oldman_health/utils/family_add_assist.dart';
import 'package:flutter_oldman_health/utils/remote_control_utils.dart';
import 'package:flutter_oldman_health/utils/utils.dart';
import 'package:flutter_oldman_health/widget/common_container.dart';
import 'package:flutter_oldman_health/widget/uploading_photos.dart';
import 'package:images_picker/images_picker.dart';

import 'family_member_page.dart';
import 'family_member_phone_add.dart';
import 'family_remote_control_page.dart';

class FamilyMemberListPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _FamilyMemberListPageState();
}

class _FamilyMemberListPageState extends State<FamilyMemberListPage> {
  List<FamilyRelationItem> relationList;
  String content = '';
  bool isLoading = false;
  bool refresh = false;

  List<Widget> _getDataWidget() {
    List<Widget> items = []; //_getHeadList(); //
    items.add(albumButtonWidget());
    items.add(Container(
        margin: EdgeInsets.fromLTRB(16, 16, 0, 0),
        alignment: AlignmentDirectional.centerStart,
        child: Text(
          "家庭成员",
          style: TextStyle(fontSize: 18, color: Color(0xffaaaaaa)),
        )));

    if (null == relationList || relationList.isEmpty) {
      items.add(isLoading
          ? Container(
              width: double.infinity,
              height: 450,
              alignment: Alignment.center,
              child: const CircularProgressIndicator())
          : Container(
              padding: EdgeInsets.only(top: 100),
              alignment: Alignment.center,
              child: Text("请添加成员",
                  style: TextStyle(fontSize: 19, color: Color(0xffaaaaaa)))));
    } else {
      var tempList = relationList.map((value) {
        FamilyAddAssist().relationIdList.clear();
        FamilyAddAssist().relationIdList.add(value.memberId);
        return CommonContainer(
            GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: () async {
                  refresh = await Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => FamilyMemberPage(value)));
                  if (null != refresh && refresh) {
                    refresh = false;
                    queryFamilyRelation();
                  }
                },
                child: Row(children: <Widget>[
                  Image.asset('images/ic_family_member_head.png',
                      width: 32, height: 32),
                  Expanded(
                      flex: 1,
                      child: Container(
                          margin: EdgeInsets.only(left: 18),
                          child: Text(
                            value.alias,
                            style: TextStyle(fontSize: 19),
                          ))),
                  Icon(Icons.arrow_forward_ios, color: Color(0xFFAAAAAA))
                ])),
            margin: EdgeInsets.only(top: 12),
            padding: EdgeInsets.all(16));

        // return ListTile(
        //   title: Text(value["title"]),
        //   leading: Image.network(value["imageUrl"]),
        //   subtitle: Text(value["author"]),
        // );
      });
      items.addAll(tempList.toList());
    }
    return items;
  }

  Future<bool> queryFamilyRelation() async {
    isLoading = true;
    var response = await FamilyMemberService.queryFamilyRelation();
    if (null != response && response.statusCode == 200) {
      if (response.data.toString().contains("User has not logged in yet")) {
        Navigator.pushReplacement(
            context, MaterialPageRoute(builder: (context) => LoginPage()));
      }
      FamilyRelationModel familyRelationModel =
          FamilyRelationModel.fromJson(response.data);
      setState(() {
        isLoading = false;
        relationList = familyRelationModel.data;
      });
    }
    return null != response && response.statusCode == 200;
  }

  @override
  void dispose() {
    super.dispose();
    EventBus().off("UploadPhotosEvent");
    FamilyAddAssist().offEventBus();
  }

  String userId = "";
  FamilyRemoteControlPage familyRemoteControlPage;

  @override
  void initState() {
    super.initState();
    if (null == relationList || relationList.isEmpty) queryFamilyRelation();

    EventBus().on("UploadPhotosEvent", (event) {
      print("eventbus UploadPhotosEvent ");
      addUpLoadPhoto(event.albumId, event.res);
    });
    EventBus().on("queryFamilyRelation", (p0) {
      queryFamilyRelation();
    });

    Future<String> userIdFuture = Utils.getStrSharePreferences("userId");
    if (userIdFuture != null) {
      userIdFuture.then((value) {
        if (null != value && value.isNotEmpty) {
          userId = value;
          RemoteControlTool().connect(value);

          EventBus().on(Constant.REMOTE_CONTROL_CONTROLLER, (event) {
            RemoteControlRequestModel model =
                RemoteControlRequestModel.fromJson(json.decode(event));

            if (null == familyRemoteControlPage) {
              familyRemoteControlPage = FamilyRemoteControlPage(
                  familyId: model.userId, active: false);

              Future<int> state =
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                return familyRemoteControlPage;
              }));
              state.whenComplete(() => familyRemoteControlPage = null);
            }
          });

          EventBus().on(Constant.DEVICE_KICK_OFF, (event) {
            print(Constant.DEVICE_KICK_OFF);
            // EasyLoading.showInfo('该账号已在别处登录');
            Navigator.pushReplacement(
                context, MaterialPageRoute(builder: (context) => LoginPage()));
          });

          FamilyAddAssist().setEventBus(context);
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    Future<void> _handleRefresh() async {
      bool load = await queryFamilyRelation();
      if (load) {
        EasyLoading.showSuccess('已刷新');
      }
    }

    return Container(
        color: Constant.backgroundColor,
        // child: ListView(children: _getDataWidget())
        child: MediaQuery.removePadding(
            context: context,
            removeTop: true,
            child: Column(
              children: [
                _getTitle(),
                Expanded(
                    flex: 1,
                    child: Container(
                      child: RefreshIndicator(
                          onRefresh: _handleRefresh,
                          color: Colors.orange,
                          backgroundColor: Colors.white,
                          child: ListView(
                              shrinkWrap: false, children: _getDataWidget())),
                      padding: EdgeInsets.fromLTRB(16, 3, 16, 0),
                    ))
              ],
            )));
  }

  _addFamilyRelation(String memberId) async {
    var response =
        await FamilyMemberService.addFamilyRelation(memberId: memberId);
    if (null != response && response.statusCode == 200) {
      ResponseDataModel<String> responseDataModel =
          ResponseDataModel.fromJson(response.data);
      if (null != responseDataModel) {
        EasyLoading.showInfo(
            responseDataModel.success() ? "成功发送添加成员请求" : responseDataModel.msg);
      }
    }
  }

  scan() async {
    var options = ScanOptions();

    BarcodeScanner.scan(options: options).then((result) {
      print("rawContent:" + result.rawContent);
      if (null != result && null != result.rawContent) {
        _addFamilyRelation(result.rawContent);
      }
    }).onError((error, stackTrace) {
      print(error);
      print(stackTrace);
      if (error.toString().contains("PERMISSION_NOT_GRANTED")) {
        EasyLoading.showInfo("请到：设置->健康监护中开启相机权限");
      }
    });
    // setState(() {
    //   content = result.rawContent;
    // });
  }

  Future addFamilyMemberDialog() async {
    var result = await showDialog(
        context: context,
        builder: (context) {
          return SimpleDialog(
            // title: Text('添加角色'),
            children: <Widget>[
              SimpleDialogOption(
                  child: Padding(
                      padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                      child: Text("二维码扫一扫添加",
                          textAlign: TextAlign.center,
                          style: TextStyle(fontSize: 18))),
                  onPressed: () async {
                    // EasyLoading.showInfo("二维码扫一扫添加");
                    Navigator.pop(context);
                    scan();
                  }),
              SimpleDialogOption(
                  child: Container(
                height: 1,
                color: Color(0xffdddddd),
              )),
              SimpleDialogOption(
                  child: Text("手机号码搜索添加",
                      textAlign: TextAlign.center,
                      style: TextStyle(fontSize: 18)),
                  onPressed: () async {
                    Navigator.pop(context);
                    bool refresh = await Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => FamilyMemberAddPage()));
                    if (refresh) {
                      queryFamilyRelation();
                    }
                  }),
            ],
          );
        });
    print("result=> $result");
    return result;
  }

  // List<Widget> _getHeadList() {
  //   return [
  //     _getTitle(),
  //     CommonContainer(
  //         GestureDetector(
  //                    behavior: HitTestBehavior.translucent,
  //             onTap: () {
  //               Navigator.push(context,
  //                   MaterialPageRoute(builder: (context) => MessageListPage()));
  //             },
  //             child: FractionallySizedBox(
  //                 widthFactor: 1,
  //                 child: Text("消息提醒",
  //                     textAlign: TextAlign.center,
  //                     style: TextStyle(
  //                         fontWeight: FontWeight.w300,
  //                         fontSize: 19,
  //                         color: Color(0xffaaaaaa))))),
  //         EdgeInsets.only(top: 20),
  //         EdgeInsets.all(16),
  //         Colors.white,
  //         Color(0xffaaaaaa),
  //         58),
  //     Container(
  //         margin: EdgeInsets.fromLTRB(16, 16, 0, 0),
  //         alignment: AlignmentDirectional.centerStart,
  //         child: Text(
  //           "家庭成员",
  //           style: TextStyle(fontSize: 18, color: Color(0xffaaaaaa)),
  //         ))
  //   ];
  // }

  Widget _getTitle([String title = "成员"]) {
    return Container(
        color: Constant.appbarColor,
        padding: EdgeInsets.fromLTRB(8, 46, 8, 8),
        child: FractionallySizedBox(
            widthFactor: 1,
            child: Stack(alignment: Alignment.center, children: [
              Padding(
                  padding: EdgeInsets.only(top: 5, bottom: 5),
                  child: Text(title,
                      textAlign: TextAlign.center,
                      style: TextStyle(fontSize: 22, color: Colors.black87))),
              Positioned(
                  right: 4,
                  child: GestureDetector(
                      behavior: HitTestBehavior.translucent,
                      onTap: () {
                        addFamilyMemberDialog().then((value) {
                          print(value);
                        });
                        // .then((value) => print(value));
                      },
                      child: Container(
                          padding: EdgeInsets.fromLTRB(22, 11, 16, 8),
                          child: Image.asset("images/ic_family_member_add.png",
                              width: 24, height: 24))))
            ])));
  }

  Widget messageButtonWidget() {
    return CommonContainer(
        GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => MessageListPage()));
            },
            child: FractionallySizedBox(
                widthFactor: 1,
                child: Text("消息提醒",
                    textAlign: TextAlign.center,
                    style: TextStyle(
                        fontWeight: FontWeight.w300,
                        fontSize: 19,
                        color: Color(0xffaaaaaa))))),
        margin: EdgeInsets.only(top: 20),
        padding: EdgeInsets.all(16),
        colorBg: Colors.white,
        colorBorder: Color(0xffaaaaaa),
        radiusCircular: 58);
  }

  // 全局上传图片
  Widget albumButtonWidget() {
    return CommonContainer(
        GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => AlbumPage()));
            },
            child: FractionallySizedBox(
                widthFactor: 1,
                child: Text("相册",
                    textAlign: TextAlign.center,
                    style: TextStyle(
                        fontWeight: FontWeight.w300,
                        fontSize: 19 //color: Color(0xffaaaaaa)
                        )))),
        margin: EdgeInsets.only(top: 20),
        padding: EdgeInsets.all(16),
        colorBg: Colors.white,
        colorBorder: Color(0xffaaaaaa),
        radiusCircular: 58);
  }

  addUpLoadPhoto(String albumId, List<Media> res) {
    int resAdd = UploadingPhotos().addUpLoadPhoto(albumId, res);
    if (1 != resAdd) {
      //EasyLoading.showInfo(resAdd == 0 ? "请添加照片" : "请上传结束后再上传图片");
    } else {
      EventBus().emit("UploadCallbackEvent", true);
      UploadingPhotos().upLoadPhoto();
    }
  }
}
